#!/usr/bin/env python
"""
UserConf.py

Read in Athabaskan's config file. If it doesn't exist,
use default settings.
"""

def _(s): return s

import ConfigParser, os, wx
from frontend.dialogs import UserMessage

class UserSettings:
    _shared_state = {}
    def __init__(self):
        self.__dict__ = self._shared_state
    
    def setState(self):
        d = wx.StandardPaths.Get().GetUserDataDir()
        self.cfile = "%s.conf" % wx.GetApp().GetAppName().lower()
        self.cfile = os.path.join(d, self.cfile)
        self.config = ConfigParser.ConfigParser()
        self.doRead = False
        self.doWrite = False
        self.err = None
#        self.window_position_x = 0
#        self.window_position_y = 0
#        self.window_size_width = wx.GetDisplaySize()[0]
#        self.window_size_height = wx.GetDisplaySize()[1]
        self.hist = []
        self.dbs = []
        
        if os.path.exists(d):
            if os.path.exists(self.cfile):
                try:
                    f = open(self.cfile, "r")
                    f.close()
                    self.doRead = True
                    try:
                        f = open(self.cfile, "a")
                        f.write("")
                        f.close()
                        self.doWrite = True
                    except (IOError, OSError), msg:
                        self.err = msg
                except (IOError, OSError), msg:
                    self.err = msg
            else:
                try:
                    f = open(self.cfile, "w")
                    self.doWrite = True
                except (IOError, OSError), msg:
                    self.err = msg
        else:
            try:
                os.mkdir(d, 0755)
                try:
                    f = open(self.cfile, "w")
                    f.write("")
                    f.close()
                    self.doWrite = True
                except (IOError, OSError), msg:
                    self.err = msg
            except (IOError, OSError), msg:
                self.err = msg
        
        if self.doRead:
            try:
                self.createInternal()
                self.config.read([self.cfile])
                self.setInternal()
            except (IOError, OSError), msg:
                self.err = msg
                self.createInternal()
        else:
            self.createInternal()
            
        return self
    
    def createInternal(self):
        sects = self.config.sections()
        li =  ["FileHistory", "Databases", "WindowSettings"]
        for i in li:
            if i not in sects:
                self.config.add_section(i)
    
    def setInternal(self):
        dct =  {"FileHistory":self.hist, "Databases":self.dbs}
        for (key, value) in dct.items():
            self.syncList(key, value, 1)
    
    def anyErrors(self):
        if self.err != None:
            UserMessage.say(self.err, "Error", wx.ICON_ERROR)
            self.err = None
    
    def getWindowSize(self):
        return (500, 400)
    
    def getWindowPosition(self):
        return wx.BOTH
    
    def fileHistoryList(self):
        return self.hist[:]
    
    def lastFile(self):
        if len(self.hist) != 0:
            return self.hist[-1]
        return None
    
    def updateHistory(self, current):
        if current not in self.hist:
            if len(self.hist) >= 5:
                self.hist = self.hist[1:]
            self.hist.append(current)
        else:
            self.hist.remove(current)
            self.hist.append(current)
        self.syncList("FileHistory", self.hist, 2)
    
    def databaseList(self):
        return self.dbs
    
    def addDBs(self, names):
        for name in names:
            if name not in self.dbs:
                self.dbs.append(name)
                self.dbs.sort()
                self.syncList("Databases", self.dbs, 2)
    
    def removeDBs(self, names):
        for name in names:
            if name in self.dbs:
                self.dbs.remove(name)
                self.syncList("Databases", self.dbs, 2)
    
    def syncList(self, sect, lst, memo):
         lst2 = self.config.items(sect)
         if memo == 1:
             if len(lst) < len(lst2):
                 lst2.sort()
                 for (name, value) in lst2:
                     if value not in lst:
                         lst.append(value)
             else:
                 for i in range(len(lst)):
                     self.config.set(sect, str(i), lst[i])
         else: # memo == 2:
             if len(lst) < len(lst2):
                 lst2.sort()
                 for (name, value) in lst2:
                     if value not in lst:
                         self.config.remove_option(sect, name)
             else:
                 for i in range(len(lst)):
                     self.config.set(sect, str(i), lst[i])
    
    def writeConf(self, current):
        if os.path.exists(str(current)):#HMMMM
            try:
                self.updateHistory(current)
                self.config.write(open(self.cfile, "w"))
            except (OSError, IOError), msg:
                if self.doWrite:
                    self.err = msg
    
if __name__ == "__main__":
    app = wx.PySimpleApp()
    wx.GetApp().SetAppName("athabaskan")
    uc = UserConf()
    
